        //第一页
        //校验用户输入值是否正确
        let username=document.querySelector("#userName");
        let phone=document.querySelector("#phoneNum");
        let idNum=document.querySelector("#IDNum");
        function  verify(){
        //对输入值进行校验
        if(username.value&&(/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/ .test(phone.value))
            &&(/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/  .test(idNum.value)) ){
                // console.log("校验成功");
                return true;
            }else{
                alert("请输入正确的用户名/电话号码/身份证号");
            }
        }


        async function renderSelect() {
            let { result: { list: data } } = await ajax({
                url: "http://newshopapi.0melon0.cn/api/f_user/chooselist",
                params: {
                    token: localStorage.getItem("token")
                }
            })
            // console.log("可预约列表", data)
            let html = ``;
            data.forEach((el, idx) => {
                let state = '';
                if (idx == 0) {
                    state = 'selected'
                }
                // 注意. 要把 值 放在value, 否则 change 事件内获取不到
                html += `<option value="${el.day_time}" ${state}>${el.day_time}</option>
                `
            })
            slt_box.innerHTML = html;
            // 渲染第一天的场次详情
            renderList(data[0].day_time)
        }


        async function renderList(day_time) {
            let day_detail = await ajax({
                url: 'http://newshopapi.0melon0.cn/api/f_user/chooseday',
                params: {
                    token: localStorage.getItem("token"),
                    // 简写属性
                    day_time
                }
            })
            let html = ``;
            day_detail.result.list.forEach((el, idx) => {//将需要的信息拼接到btn 
                html += `<li>
                    <span>${el.show_name}</span>
                    <button class="secondBtn" data-time=${el.show_name} data-date=${el.day_time} data-showid=${el.show_id}>预约</button>
                </li>`
            })
            chooseList.innerHTML = html;
        }



        let homepage=document.querySelector(".homePage");
        let orderpage=document.querySelector(".orderPage");
        let codepage=document.querySelector(".codePage");
        let myorder=document.querySelector(".myOrder");
        let noorder=document.querySelector(".noOrder");

        let chooseList=document.querySelector(".orderPage .list")
        console.log(chooseList);
        let slt_box=document.querySelector(".orderPage .select-Date");

        let startBtn=document.querySelector("#startorderBtn");
        let myBtn=document.querySelector("#myorderBtn");
  
        
        let aptDate=document.querySelector("#aptDate");
        let aptTime=document.querySelector("#aptTime");
        let tipShowId = document.querySelector("#tipShowId");
        let clbtn=document.querySelector("#cancelBtn");
        let cmbtn=document.querySelector("#confirmBtn");
        let tip = document.querySelector(".orderPage .tip");

        // 第三页
        let visitor=document.querySelector(".visitor");
        let code=document.querySelector(".code");

        let reBtn=document.querySelector("#reBtn");
        let ctnBtn=document.querySelector("#ctnBtn");
        let rcBtn=document.querySelector("#rcBtn");
        
        let reBtn2=document.querySelector("#reBtn2");
        // 点击“开始预约”
        startBtn.addEventListener("click", async () => {
            if (verify()==true) {
                let register = await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/register',
                    method: "POST",
                    params: {
                        name: `${username.value}`,
                        phone: `${phone.value}`,
                        card: `${idNum.value}`
                    }
                })
                let token = register.result.token;
                // 将 token 存至 storage 供后续使用
                localStorage.setItem("token", token);
                localStorage.setItem("username",username.value);
                localStorage.setItem("phone",phone.value)
                // 跳转至第二个页面并请求可预约场次
                homepage.style.display="none";
                orderpage.style.display="block";
                renderSelect()
            }
        })


        //点击“我的预约”
        myBtn.addEventListener("click",async (event) => {
            //校验通过，展示我的预约，隐藏首页 (更新)
            if(verify() ){
            homepage.style.display="none";
            myorder.style.display="block";
            //每次展示之前，清空之前查询结果 (更新)
            orderBox.innerHTML ="";
            console.log("查询预约结果");
            let res = await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/report',
                    method: "POST",
                    params: {
                        //应该取当前录入的值,而不是存储里的值 (更新)
                        name: username.value,
                        phone: phone.value,
                    }
                });
                    console.log("没有预约结果");
                
                 console.log(res);
                let html = ``;
                res.result.forEach(function(el){
                    let sestime='';
                    if(el.show_id==1){
                        sestime='09:00-12:00';
                    }else if(el.show_id==2){
                        sestime='12:00-14:30';
                    }else{
                        sestime='14:30-17:00';
                    }
                    html+=`<div class="orderList">
                    <div class="uname">姓名：${el.name}</div>
                    <div class="udata">日期：${el.day_time}</div> 
                    <div class="usession">场次：${sestime}</div>
                    <button class="myqrcode" data-id=${el.id}>点击查看二维码</button>
                    </div>`

            })
            orderBox.innerHTML = html;
            }
            
        });






        

        // ------预约页事件------
        // 下拉框变化修改场次详情
        slt_box.addEventListener("change", async function () {
            let id = loading.start(".orderPage .list")
            await sleep(1000)
            await loading.end(id);
            renderList(this.value);
        })
        // 使用事件代理添加预约按钮功能
        chooseList.addEventListener("click", async (event) => {
            let isbtn = event.target.classList.contains("secondBtn");
            if (isbtn) {
                let { time,date, showid } = event.target.dataset;
                tip.classList.add("tip-active");
                //先清空再拼接最新预约日期和时间,赋值预约id 
                tipShowId.value = showid;
                aptTime.value=time;
                aptDate.value = date;
                aptDate.innerHTML = "";
                aptTime.innerHTML = "";
                aptDate.innerHTML = "日期："+date;
                aptTime.innerHTML = "时间："+time;

                // console.log("预约结果", res);
            }
        })
        //取消预约按钮事件 
        cancelBtn.addEventListener("click", async (event) => {
          
            tip.classList.remove("tip-active"); 
        });

        //确认预约后，调用预约接口 
        confirmBtn.addEventListener("click", async (event) => {

            let res = await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/bookday',
                    method: "POST",
                    params: {
                        token: localStorage.getItem("token"),
                        // 简写属性
                        day_time: aptDate.value,
                        show_id: tipShowId.value
                    }
                });
                // console.log("预约结果", res);
                orderpage.style.display="none";
                codepage.style.display="block";

                visitor.innerHTML=res.result.name;
                let codeRes= await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/Qrcode',
                    method: "GET",
                    params: {
                        token: localStorage.getItem("token"),
                        // 简写属性
                        id: res.result.id
                    }
                });
                console.log(codeRes);
                console.log(codeRes.data.data);
                code.innerHTML=`<img src="${codeRes.data.data}" alt="" class="imgstyle">`;

        });


        //二维码界面，添加按钮点击事件
        reBtn.addEventListener("click",async (event) => {
            codepage.style.display="none";
            homepage.style.display="flex";
        });

        ctnBtn.addEventListener("click",async (event) => {
            codepage.style.display="none";
            orderpage.style.display="block";
            //需要去掉显示样式，而不是通过display (更新)
            tip.classList.remove("tip-active");
        });

        let uname=document.querySelector(".uname");
        let udata=document.querySelector(".udata");
        let usession=document.querySelector(".usession");
        let orderBox=document.querySelector(".orderBox");
        rcBtn.addEventListener("click",async (event) => {
            codepage.style.display="none";
            myorder.style.display="block";
            // console.log(localStorage.getItem("phone"));
            // console.log(localStorage.getItem("username"));
            let res = await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/report',
                    method: "POST",
                    params: {
                        name:localStorage.getItem("username"),
                        phone:localStorage.getItem("phone")
                    }
                });
                // console.log(res);
                let html = ``;
            res.result.forEach(function(el){
                let sestime='';
                if(el.show_id==1){
                    sestime='09:00-12:00';
                }else if(el.show_id==2){
                    sestime='12:00-14:30';
                }else{
                    sestime='14:30-17:00';
                }
                html+=`<div class="orderList">
                <div class="uname">姓名：${el.name}</div>
                <div class="udata">日期：${el.day_time}</div> 
                <div class="usession">场次：${sestime}</div>
                <button class="myqrcode" data-id=${el.id}>点击查看二维码</button>
            </div>`

            })
            orderBox.innerHTML = html;
        });

        let myqrcode=document.querySelector(".myqrcode");
        let showCode=document.querySelector(".showCode");
        let shade=document.querySelector(".shade");
        myorder.addEventListener("click",async (event)=>{
            if(event.target.classList.contains("myqrcode")){
                console.log(111)
                let qrRes= await ajax({
                    url: 'http://newshopapi.0melon0.cn/api/f_user/Qrcode',
                    method: "GET",
                    params: {
                        token: localStorage.getItem("token"),
                        id: event.target.dataset.id
                    }
                });
                console.log(qrRes.data.data);
                showCode.style.display="block";
                shade.style.display="block";
                showCode.innerHTML=`<img src="${qrRes.data.data}" alt="">`;
            }
            
        })
        window.addEventListener("click",()=>{
            showCode.style.display="none";
            shade.style.display="none";
        })
    
       //最后一页“返回首页按钮”
       reBtn2.addEventListener("click",async (event) => {
            myorder.style.display="none";
            homepage.style.display="flex";
        });

        //封装ajax
        function formatParams(params) {
            let paramsArr = [];
            for (let key in params) {
                let item = `${key}=${params[key]}`;
                paramsArr.push(item)
            }
            return paramsArr.length ? `${paramsArr.join("&")}` : '';
        }
        function ajax({ url, method = "GET", params }) {
            return new Promise((resolve, reject) => {
                let xml = new XMLHttpRequest();
                xml.addEventListener("readystatechange", () => {
                    if (xml.readyState !== 4) {
                        return
                    }
                    if (xml.status == 200) {
                        // 数据
                        // xml.response;
                        resolve(JSON.parse(xml.response))
                    } else {
                        reject()
                    }
                })
                // 处理 get post 参数
                if (method == "GET" || method == "get") {
                    let getParams = formatParams(params);
                    url += getParams ? '?' + getParams : '';
                    xml.open(method, url);
                    xml.send();
                } else {
                    xml.open(method, url);
                    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xml.send(formatParams(params));
                }
            })
        };


        function sleep(interval) {
            return new Promise(resolve => {
                setTimeout(resolve, interval);
            })
        }
        let loading = {
            count: 0,
            itemList: [],
            start(el, duration) {
                if (!el) {
                    console.error("缺乏容器选择器")
                }
                let box = document.querySelector(el);
                let load = document.createElement("div");
                box.style.position = "relative";
                load.className = "loader_mask fadeIn";
                load.style.cssText = `
                                    width:100%;height:100%;position: absolute;top:0;left:0;`
                load.innerHTML = `<div class="loader"></div>`
                box.appendChild(load)
                let loadId = ++this.count;
                let curInfo = {
                    id: loadId,
                    dom: load
                }
                this.itemList.push(curInfo);
                // 如果是定时关闭, 则自动调用 end
                if (duration && typeof duration === "number") {
                    setTimeout(() => {
                        this.end(loadId)
                    }, duration)
                }
                return loadId
            },
            async end(id = 10) {
                if (!id) {
                    console.error("缺乏动画id")
                }
                let item = this.itemList.find(el => el.id == id);
                if (!item) {
                    console.error("动画不存在")
                    return
                }
                item.dom.classList.add("fadeOut")
                await sleep(300)
                item.dom.remove();
                let index = this.itemList.findIndex(el => el.id == id);
                this.itemList.splice(index, 1);
            }
        }

        
       









